import { useState, useRef, useEffect } from 'react';

type ToastType = 'success' | 'error';

// 提示弹窗api
export function messageApi() {
    const [show, setShow] = useState(false);
    const [message, setMessage] = useState('');
    const [type, setType] = useState<ToastType>('success');
    const timeoutRef = useRef<number | null>(null);

    const showToast = (msg: string, toastType: ToastType = 'success') => {
        if (timeoutRef.current) clearTimeout(timeoutRef.current);
        setMessage(msg);
        setType(toastType);
        setShow(true);
        timeoutRef.current = window.setTimeout(() => setShow(false), 3000);
    };

    useEffect(() => {
        return () => {
            if (timeoutRef.current) clearTimeout(timeoutRef.current);
        };
    }, []);

    return { show, message, type, showToast };
}